package peer.tools;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import peer.p2pnet.message.TimeSynMessage;
import peer.p2pnet.message.TimeSynMessage2;

public class VTime implements Runnable{
	Thread mainThread;
	Thread synTimeThread;
	InetAddress ip;
	int port;
	long nowTime=System.currentTimeMillis();
	public static void main(String[] args) throws UnknownHostException{
		InetAddress cIp=InetAddress.getByName("192.168.65.1");
		int cPort=55555;
		new VTime(cIp,cPort);
	}
	
	public VTime(InetAddress ip,int port){
		this.ip=ip;
		this.port=port;
		mainThread=new Thread(this);
		mainThread.start();
		synTimeThread=new Thread(){
			public void run(){
				while(true){
					synNow();
					try {
						Thread.sleep(1000*60*60*12);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		synTimeThread.start();
	}
	
	public void run(){
		while(true){
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				continue;
			}
			nowTime+=1000;
		}
	}
	
	public void synNow(){
		new Thread(){
			public void run(){
				DatagramSocket ds=null;
				try {
					ds=new DatagramSocket();
					ds.setSoTimeout(3000);
				} catch (SocketException e) {
					return;
				}
				byte[] data=new byte[1024];
				DatagramPacket dp=new DatagramPacket(data,data.length);
				TimeSynMessage tsm=new TimeSynMessage();
				tsm.setDstAddress(ip);
				tsm.setDstPort(port);
				for(int i=0;i<3;i++){
					i++;
					try {
						ds.send(tsm.getDatagramPacket());
						ds.receive(dp);
						if(peer.tools.MessageCheck.checkSType(dp)==peer.tools.MessageType.sType_TimeSynMessage2){
							TimeSynMessage2 stm2=new TimeSynMessage2(dp);
							nowTime=stm2.getTime();
							mainThread.interrupt();
							return;
						}
					} catch (IOException e) {
						//e.printStackTrace();
					}
				}
			}
		}.start();
	}
	
	public long getCurrentTime(){
		return nowTime;
	}

}
